package io.lkt.modules.sys.controller;

import io.lkt.common.util.Query;
import io.lkt.common.utils.DateUtil;
import io.lkt.common.utils.DateUtilPlus;
import io.lkt.common.utils.PageUtils;
import io.lkt.common.utils.R;
import io.lkt.common.validator.ValidatorUtils;
import io.lkt.modules.sys.entity.BOrderInfoEntity;
import io.lkt.modules.sys.entity.SysUserEntity;
import io.lkt.modules.sys.entity.SysUserGzhEntity;
import io.lkt.modules.sys.entity.VipOrderAnalyseEntity;
import io.lkt.modules.sys.service.BOrderInfoService;
import io.lkt.modules.sys.service.SysUserRoleService;
import io.lkt.modules.sys.service.SysUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 *
 *
 * @author xss
 * @email dustwas@163.com
 * @date 2019-04-29 15:04:53
 */
@RestController
@RequestMapping("/sys/borderinfo")
public class BOrderInfoController extends AbstractController{
    @Autowired
    private BOrderInfoService bOrderInfoService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("sys:borderinfo:list")
    public R list(@RequestParam Map<String, Object> params){
        System.out.println(params);
        SysUserEntity curUser= getUser();
        params.put("curUserId",curUser.getUserId());
        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(curUser.getUserId());
        params.put("userGzhList", userGzhList);
        Query query = new Query(params);

        List<BOrderInfoEntity> list=bOrderInfoService.queryList(query);

        if (CollectionUtils.isNotEmpty(list)) {
            for (BOrderInfoEntity info: list) {
                if(info.getItemName() == null || info.getItemName().equals("")){
                    BOrderInfoEntity bOrderInfo = bOrderInfoService.getById(info.getOrderId());
                    info.setItemName(bOrderInfo.getSubject());
                }
            }
        }

        Integer total=bOrderInfoService.queryTotal(query);
        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());

        return R.ok().put("page", page);
    }

    /**
     * 获取当前登录用户负责的公众号中待支付的订单数量
     * @return 待支付的订单数量
     */
    @RequestMapping("/prePayCount")
    public R prePayCount() {
        Map<String, Object> params = new HashMap<>();
        SysUserEntity curUser= getUser();
        Long userId = curUser.getUserId();
        params.put("curUserId",userId);
        // 获取系统用户负责的公众号
        List<String> sysUserGzhList = sysUserService.getUserGzhList(userId);
        params.put("sysUserGzhList", sysUserGzhList);

        Integer total = bOrderInfoService.queryPrepayTotal(params);
        String latestDetail = "";
        if (total.intValue() > 0) {

            BOrderInfoEntity orderInfo = bOrderInfoService.getLatestPrepayOrder(params);
            String latestTime = new SimpleDateFormat("HH:mm:ss").format(orderInfo.getCreateTime());
            latestDetail = latestTime + "  " + orderInfo.getUserName() + "  " + orderInfo.getTotalAmount() + "元";
        }
        return R.ok().put("latestCount", total).put("latestDetail", latestDetail);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{orderId}")
    //@RequiresPermissions("sys:borderinfo:info")
    public R info(@PathVariable("orderId") String orderId){
        BOrderInfoEntity bOrderInfo = bOrderInfoService.getInfo(orderId);

        return R.ok().put("bOrderInfo", bOrderInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:borderinfo:save")
    public R save(@RequestBody BOrderInfoEntity bOrderInfo){
        bOrderInfoService.save(bOrderInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("sys:borderinfo:update")
    public R update(@RequestBody BOrderInfoEntity bOrderInfo){
        ValidatorUtils.validateEntity(bOrderInfo);
        bOrderInfoService.updateById(bOrderInfo);

        return R.ok();
    }

    /**
     * 退款
     */
    @RequestMapping("/drawback")
    @RequiresPermissions("sys:borderinfo:update")
    public R drawback(@RequestBody BOrderInfoEntity bOrderInfo){
        ValidatorUtils.validateEntity(bOrderInfo);
        bOrderInfoService.drawback(bOrderInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:borderinfo:delete")
    public R delete(@RequestBody String[] orderIds){
        bOrderInfoService.removeByIds(Arrays.asList(orderIds));

        return R.ok();
    }

    /**
     * 多线程处理
     * @param orderId
     * @param createTime
     * @param remark
     * @return
     */
    @RequestMapping("/updateFollowStatus")
    public R updateFollowStatus(@RequestParam String orderId, @RequestParam String createTime, @RequestParam String remark) {
        if (orderId == null || orderId == "") return R.error("访问失败");
        if (createTime == null || createTime == "") return R.error("访问失败");

        Date oldTime = null;
        try {
            oldTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTime);
        } catch (Exception e) {
            return R.error("访问失败");
        }
        Date followTime = new Date();
        long followDuration = (followTime.getTime() - oldTime.getTime()) / 1000 / 60;
        synchronized (this) {
            BOrderInfoEntity bOrderInfo = bOrderInfoService.getById(orderId);
            if (bOrderInfo.getFollowStatus().intValue() == 1) {
                return R.error("该订单已经被其他用户跟进");
            }
            bOrderInfoService.updateFollowStatus(orderId, followTime, followDuration, getUserId(), remark);
        }
        return R.ok();
    }

    /**
     * 获取系统用户的订单跟进情况列表
     * @param params
     * @return
     */
    @RequestMapping("/sysUserFollow")
    public R sysUserFollow(@RequestParam Map<String, Object> params) {
        if (StringUtils.isNotBlank(params.get("endDate").toString())) {
            params.put("endDate", params.get("endDate").toString() + " 23:59:59");
        }
        if (StringUtils.isBlank(params.get("beginDate").toString())) {
            // 从本月第一天到最后一天
            /*Date now = new Date();
            String firstDayOfMonth = DateUtil.getFirstDayOfMonth(now);
            String lastDayOfMoth = DateUtil.getLastDayOfMoth(now) + " 23:59:59";
            params.put("beginDate", firstDayOfMonth);
            params.put("endDate", lastDayOfMoth);*/

            // 从上周日到周六
            /*Date date = new Date();
            Date firstDayOfWeek = DateUtilPlus.getFirstDayOfWeek(date);
            Date lastDayOfWeek = DateUtilPlus.getLastDayOfWeek(date);
            String beginDate = DateUtilPlus.formatDate(firstDayOfWeek, "yyyy-MM-dd");
            String endDate = DateUtilPlus.formatDate(lastDayOfWeek, "yyyy-MM-dd") + " 23:59:59";
            params.put("beginDate", beginDate);
            params.put("endDate", endDate);*/

            // 从上周一到周日
            Date date = new Date();
            String firstDayOfWeek = DateUtil.getFirstDayOfWeek(date);
            String lastDayOfWeek = DateUtil.getLastDayOfWeek(date) + " 23:59:59";
            params.put("beginDate", firstDayOfWeek);
            params.put("endDate", lastDayOfWeek);
        }

        /*params.put("curUserId",getUserId());
        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(getUserId());
        params.put("userGzhList", userGzhList);*/

        List<Long> userIdList = new LinkedList<>();
        // 1、获取单位时间内，平台用户的有效跟进订单关于平台用户的跟进次数、跟进积分汇总
        List<SysUserEntity> validFollowOrderSummaryList = bOrderInfoService.getValidFollowOrderSummaryList(params);
        // 2、获取单位时间内，平台用户的有效成交订单号
        List<SysUserEntity> validDealedOrderSummaryList = bOrderInfoService.getValidDealedOrderSummaryList(params);

        if (CollectionUtils.isNotEmpty(validFollowOrderSummaryList)) {
            for (SysUserEntity entity : validFollowOrderSummaryList) {
                userIdList.add(entity.getUserId());
            }
        }

        if (CollectionUtils.isNotEmpty(validDealedOrderSummaryList)) {
            for (SysUserEntity entity : validDealedOrderSummaryList) {
                Long userId = entity.getUserId();
                if (!userIdList.contains(userId)) {
                    userIdList.add(entity.getUserId());
                }
            }
        }

        if (userIdList.size() == 0) {
            return R.error("无记录");
        }

        params.put("userIdList", userIdList);
        Query query = new Query(params);
        List<SysUserEntity> list = bOrderInfoService.getSysUserFollowList(query);

        if (CollectionUtils.isNotEmpty(list)) {
            for (SysUserEntity entity : list) {
                Long userId = entity.getUserId();
                // 插入跟进次数和跟进积分
                if (CollectionUtils.isNotEmpty(validFollowOrderSummaryList)) {
                    for (SysUserEntity followEntity : validFollowOrderSummaryList) {
                        Long followUserId = followEntity.getUserId();
                        if (userId.equals(followUserId)) {
                            entity.setFollowCount(followEntity.getFollowCount());

                            Integer followScore = followEntity.getFollowScore();
//                            entity.setFollowScore(followScore);
                            entity.setTotalScore(Optional.ofNullable(followScore).orElse(0));
                            break;
                        }
                    }
                }

                // 插入成交订单数和成交订单积分
                if (CollectionUtils.isNotEmpty(validDealedOrderSummaryList)) {
                    for (SysUserEntity dealedEntity : validDealedOrderSummaryList) {
                        Long dealedUserId = dealedEntity.getUserId();
                        if (userId.equals(dealedUserId)) {
                            entity.setDealedCount(dealedEntity.getDealedCount());

                            Integer dealedScore = dealedEntity.getDealedScore();
                            entity.setDealedScore(dealedScore);
                            Integer totalScore = Optional.ofNullable(entity.getTotalScore()).orElse(0);
                            entity.setTotalScore(totalScore + Optional.ofNullable(dealedScore).orElse(0));
                            break;
                        }
                    }
                }
            }
        }

        // 排序: 按总得分降序排列
        Collections.sort(list, (SysUserEntity u1, SysUserEntity u2) -> u2.getTotalScore().compareTo(u1.getTotalScore()));

        int total = bOrderInfoService.getSysUserFollowListTotal(query).intValue();

        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("page", page);
    }

    /**
     * 根据用户 ID 获取系统用户的订单跟进情况列表
     * @param params
     * @return
     */
    @RequestMapping("/followInfoByUserId")
    public R followInfoByUserId(@RequestParam Map<String, Object> params) {
        if (StringUtils.isNotBlank(params.get("endDate").toString())) {
            params.put("endDate", params.get("endDate").toString() + " 23:59:59");
        }
        if (StringUtils.isBlank(params.get("beginDate").toString())) {
            // 从本月第一天到最后一天
            /*Date now = new Date();
            String firstDayOfMonth = DateUtil.getFirstDayOfMonth(now);
            String lastDayOfMoth = DateUtil.getLastDayOfMoth(now) + " 23:59:59";
            params.put("beginDate", firstDayOfMonth);
            params.put("endDate", lastDayOfMoth);*/

            // 从上周日到周六
            /*Date date = new Date();
            Date firstDayOfWeek = DateUtilPlus.getFirstDayOfWeek(date);
            Date lastDayOfWeek = DateUtilPlus.getLastDayOfWeek(date);
            String beginDate = DateUtilPlus.formatDate(firstDayOfWeek, "yyyy-MM-dd");
            String endDate = DateUtilPlus.formatDate(lastDayOfWeek, "yyyy-MM-dd") + " 23:59:59";
            params.put("beginDate", beginDate);
            params.put("endDate", endDate);*/

            // 从上周一到周日
            Date date = new Date();
            String firstDayOfWeek = DateUtil.getFirstDayOfWeek(date);
            String lastDayOfWeek = DateUtil.getLastDayOfWeek(date) + " 23:59:59";
            params.put("beginDate", firstDayOfWeek);
            params.put("endDate", lastDayOfWeek);
        }

        /*params.put("curUserId",getUserId());
        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(getUserId());
        params.put("userGzhList", userGzhList);*/

        List<String> orderIdList = new LinkedList<>();
        // 1、获取单位时间内，平台用户的全部跟进订单
        List<String> sysUserFollowOrderIdList = bOrderInfoService.getSysUserFollowOrderIdList(params);
        // 2、获取单位时间内，平台用户的有效成交订单号
        List<String> sysUserDealedOrderIdList = bOrderInfoService.getSysUserDealedOrderIdList(params);

        /*if (CollectionUtils.isNotEmpty(sysUserFollowOrderIdList)) {
            for (String sysUserFollowOrderId : sysUserFollowOrderIdList) {
                orderIdList.add(sysUserFollowOrderId);
            }
        }

        if (CollectionUtils.isNotEmpty(sysUserDealedOrderIdList)) {
            for (String sysUserDealedOrderId : sysUserDealedOrderIdList) {
                if (!orderIdList.contains(sysUserDealedOrderId)) {
                    orderIdList.add(sysUserDealedOrderId);
                }
            }
        }*/
        orderIdList.addAll(sysUserFollowOrderIdList);
        orderIdList.removeAll(sysUserDealedOrderIdList);// 去重
        orderIdList.addAll(sysUserDealedOrderIdList);


        if (orderIdList.size() == 0) {
            return R.error();
        }

        params.put("orderIdList", orderIdList);

        Query query = new Query(params);
        List<BOrderInfoEntity> list = bOrderInfoService.getfollowInfoByUserId(query);

        PageUtils page = new PageUtils(list, orderIdList.size(), query.getLimit(), query.getPage());
        return R.ok().put("page", page);
    }

    @RequestMapping("/vipOrderAnalyse")
    public R vipOrderAnalyse(@RequestParam Map<String, Object> params) {
        System.out.println("[vipOrderAnalyse = ]" + params);
        if (!Objects.isNull(params.get("endDate"))) {
            params.put("endDate", params.get("endDate").toString() + " 23:59:59");
        }
        List<VipOrderAnalyseEntity> list = new ArrayList<>();

        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(getUserId());
        params.put("userGzhList", userGzhList);

        Query query = new Query(params);
        List<VipOrderAnalyseEntity> partList = bOrderInfoService.getGzhVipOrderAnalyse(query);
        List<VipOrderAnalyseEntity> summaryList = bOrderInfoService.getSummaryVipOrderAnalyse(query);

        list.addAll(partList);
        list.addAll(summaryList);

        PageUtils page = new PageUtils(list, list.size(), query.getLimit(), query.getPage());

        return R.ok().put("page", page);
    }
}
